<template>
    <div>
        <button @click="startSharing">开始共享</button>
    </div>
</template>

<script setup>
import { ref } from 'vue'

let socket = null
let peerConnection = null
let stream = null

const startSharing = async () => {
    try {
        // 1. 先获取屏幕流（减少等待WebSocket的时间）
        stream = await navigator.mediaDevices.getDisplayMedia({
            video: true,
            audio: true
        })

        // 2. 初始化PeerConnection
        peerConnection = new RTCPeerConnection({
            iceServers: [
                { urls: 'stun:stun.l.google.com:19302' }
            ]
        })

        // 3. 添加媒体轨道
        stream.getTracks().forEach(track => {
            peerConnection.addTrack(track, stream)
        })

        // 4. 连接信令服务器
        socket = new WebSocket('ws://192.168.3.155:8080/websocket')

        // 等待连接就绪
        await new Promise((resolve, reject) => {
            socket.onopen = resolve
            socket.onerror = reject
            setTimeout(() => reject(new Error('WebSocket连接超时')), 5000)
        })

        // 5. 现在可以安全发送注册消息
        socket.send(JSON.stringify({
            type: 'register',
            role: 'sender'
        }))

        // 6. ICE候选处理（现在socket已就绪）  这一步在执行后await peerConnection.setLocalDescription(offer)就开始执行
        peerConnection.onicecandidate = (event) => {
            if (event.candidate && socket.readyState === WebSocket.OPEN) {
                socket.send(JSON.stringify({
                    type: 'candidate',
                    candidate: event.candidate,
                    target: 'receiver'
                }))
            }
        }

        // 7. 信令消息处理
        socket.onmessage = async (event) => {
            const data = JSON.parse(event.data)
            //重要步骤开始信令交流
            if (data.type === 'start_negotiation') {
                // 推流端创建offer
                const offer = await peerConnection.createOffer()
                // 这步骤很重要，推流端需要用peerConnection.setLocalDescription()设置创建的offer
                await peerConnection.setLocalDescription(offer) // ← 触发ICE收集
                // 推流端把offer里的sdp发送给拉流端
                safeSend({
                    type: 'offer',
                    sdp: offer.sdp,
                    target: 'receiver'
                })
            }
            else if (data.type === 'candidate') {
                await peerConnection.addIceCandidate(data.candidate)
            }
            else if (data.type === 'answer') {
                // 接收到拉流端的offer
                await peerConnection.setRemoteDescription(data)
            }
        }

    } catch (error) {
        console.error('共享失败:', error)
        stopSharing()
    }
}

// 安全的发送方法
function safeSend(data) {
    if (socket?.readyState === WebSocket.OPEN) {
        socket.send(JSON.stringify(data))
    } else {
        console.warn('尝试在WebSocket未就绪时发送:', data)
    }
}

const stopSharing = () => {
    stream?.getTracks().forEach(track => track.stop())
    peerConnection?.close()
    socket?.close()
}
</script>